package com.renwei.yunlong.activity.me;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.adapter.ViewpagerFragmentAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.KnowDetailsBean;
import com.renwei.yunlong.event.KnowCommentRefreshEvent;
import com.renwei.yunlong.event.KnowCommentReplyEvent;
import com.renwei.yunlong.fragment.KnowCommentFrament;
import com.renwei.yunlong.fragment.KnowInformationFragment;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.CheckSoftInputLayout;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class KnowInformationActivity extends BaseActivity implements View.OnClickListener, CheckSoftInputLayout.OnResizeListener, TextWatcher {

    @Bind(R.id.tv_input)
    TextView tvInput;
    @Bind(R.id.card_input)
    CardView cardInput;
    @Bind(R.id.iv_comment)
    ImageView ivComment;
    @Bind(R.id.tv_bar)
    TextView tvBar;
    @Bind(R.id.rl_comment)
    RelativeLayout rlComment;
    @Bind(R.id.iv_collection)
    ImageView ivCollection;
    @Bind(R.id.tv_animation)
    TextView tvAnimation;
    @Bind(R.id.tv_collection)
    TextView tvCollection;
    @Bind(R.id.ll_collection)
    LinearLayout llCollection;
    @Bind(R.id.ll_show)
    LinearLayout llShow;
    @Bind(R.id.et_input)
    EditText etInput;
    @Bind(R.id.bt_send)
    Button btSend;
    @Bind(R.id.card_send)
    CardView cardSend;
    @Bind(R.id.ll_send)
    LinearLayout llSend;
    @Bind(R.id.root_layout)
    CheckSoftInputLayout rootLayout;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    private String knowledgeId;
    private boolean LIKE_CHECK;
    private String parentId;
    private int recodeNum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_know_information);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        ButterKnife.bind(this);

        EventBus.getDefault().register(this);
        // 设置点击其他地方输入法不隐藏
        showInput = false;

        knowledgeId = getIntent().getStringExtra("knowledgeId");

        // 增加浏览次数
        addNumView();

        initView();
        initData();
    }

    private void addNumView() {
        HashMap<String, String> map = new HashMap<>();
        map.put("knowledgeId", knowledgeId + "");
        ServiceRequestManager.getManager().
                setKnowNumView(mContext, JsonMapUtil.mapToJson(map), null);
    }

    private void initView() {
        List<Fragment> list = new ArrayList<>();
        list.add(new KnowInformationFragment(knowledgeId));
        list.add(new KnowCommentFrament(knowledgeId));
        viewPager.setAdapter(new ViewpagerFragmentAdapter(getSupportFragmentManager(), list));

        // 设置输入法弹出监听
        rootLayout.setOnResizeListener(this);
        // 限制表情不让输入
        etInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(200), AppHelper.emojiFilter});
        // 设置edittext监听
        etInput.addTextChangedListener(this);
        cardInput.setOnClickListener(this);
        rlComment.setOnClickListener(this);
        llCollection.setOnClickListener(this);
        btSend.setOnClickListener(this);
    }

    private void initData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("knowledgeId", knowledgeId);
        if ("1".equals(companyType)) {
            map.put("createUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("createUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        ServiceRequestManager.getManager().getKnowDetails(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.card_input: // 点击弹出输入法
                etInput.setHint("请文明措辞，可能会红哦~");
                showInputAnimation();
                break;
            case R.id.rl_comment: // 评论页面
                viewPager.setCurrentItem(1);
                break;
            case R.id.ll_collection: // 收藏
                if (LIKE_CHECK) {
                    setCollection(2);
                } else {
                    setCollection(1);
                }
                break;
            case R.id.bt_send: // 发布评论
                sendComment();
                break;
        }
    }

    //发布评论
    private void sendComment() {
        String s = etInput.getText().toString();
        if (TextUtils.isEmpty(s)) {
            showCenterInfoMsg("评论内容不能为空");
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("recordUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("recordUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        map.put("knowledgeId", knowledgeId);
        map.put("recordContent", s);
        map.put("parentId", parentId);
        ServiceRequestManager.getManager().sendComment(this, JsonMapUtil.mapToJson(map), this);
    }

    // 输入框
    private void showInputAnimation() {
        ScaleAnimation animation = new ScaleAnimation(1f, 1.4f, 1f, 1f);
        animation.setDuration(200);
        animation.setFillAfter(false);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                llShow.setVisibility(View.GONE);
                llSend.setVisibility(View.VISIBLE);
                // 弹出输入框
                etInput.setFocusable(true);
                etInput.setFocusableInTouchMode(true);
                etInput.requestFocus();
                CommonUtils.showKeyboard(mContext, etInput);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        cardInput.startAnimation(animation);
    }

    private void setCollection(int flag) {
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            map.put("createUserId", ownerBean.getRows().getEmployeeId());
        } else if ("2".equals(companyType)) {
            map.put("createUserId", serviceLoginBean.getRows().getEmployeeId());
        }
        map.put("knowledgeId", knowledgeId);
        //标识 1.收藏 2.取消收藏
        map.put("flag", flag + "");
        ServiceRequestManager.getManager().setKnowLike(mContext, JsonMapUtil.mapToJson(map), this);
    }

    private void collectionAnimation() {
        tvAnimation.setVisibility(View.VISIBLE);
        AnimationSet animationSet = new AnimationSet(true);
        AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);
        alphaAnimation.setDuration(500);
        animationSet.addAnimation(alphaAnimation);
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f,  //X轴的开始位置
                Animation.RELATIVE_TO_SELF, 0f,  //X轴的结束位置
                Animation.RELATIVE_TO_SELF, 0f,  //Y轴的开始位置
                Animation.RELATIVE_TO_SELF, -1.0f);  //Y轴的结束位置
        translateAnimation.setDuration(500);
        animationSet.addAnimation(translateAnimation);
        animationSet.setFillAfter(true);
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                LIKE_CHECK = true;
                tvCollection.setTextColor(getResources().getColor(R.color.color_f2ae47));
                tvCollection.setText(Integer.parseInt(tvCollection.getText().toString()) + 1 + "");
                ivCollection.setImageResource(R.mipmap.icon_know_collection_pre);
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        tvAnimation.startAnimation(animationSet);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onCommentReplyEvent(KnowCommentReplyEvent event) {
        parentId = event.getParentId();
        etInput.setHint("你正在回复 " + event.getUserName());
        // 弹出输入框
        showInputAnimation();
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 1: //详情内容
                KnowDetailsBean knowDetailsBean = new Gson().fromJson(result, KnowDetailsBean.class);
                if (knowDetailsBean.getMessage().getCode() == 200) {
                    KnowDetailsBean.RowsBean bean = knowDetailsBean.getRows();
                    recodeNum = Integer.parseInt(bean.getRecordNum());
                    CommonUtils.setBarTextView(tvBar, recodeNum);
//                    CommonUtils.setBarTextView(tvBar,100);
                    tvCollection.setText(bean.getFavoriteNum() + "");
                    // 收藏状态 0:未收藏，1:已收藏
                    if ("0".equals(bean.getFavoritesType())) {
                        LIKE_CHECK = false;
                        tvCollection.setTextColor(getResources().getColor(R.color.color_808080));
                        ivCollection.setImageResource(R.mipmap.icon_know_collection_nor);
                    } else if ("1".equals(bean.getFavoritesType())) {
                        LIKE_CHECK = true;
                        tvCollection.setTextColor(getResources().getColor(R.color.color_f2ae47));
                        ivCollection.setImageResource(R.mipmap.icon_know_collection_pre);
                    }
                }
                break;
            case 2: // 收藏
                CommonBean commonBean = new Gson().fromJson(result, CommonBean.class);
                if (commonBean.getMessage().getCode() == 200) {
                    if (LIKE_CHECK) {
                        LIKE_CHECK = false;
                        tvCollection.setTextColor(getResources().getColor(R.color.color_808080));
                        tvCollection.setText(Integer.parseInt(tvCollection.getText().toString()) - 1 + "");
                        ivCollection.setImageResource(R.mipmap.icon_know_collection_nor);
                    } else {
                        collectionAnimation();
                    }
                }
                break;
            case 3:// 发布评论
                CommonBean commentBean = new Gson().fromJson(result, CommonBean.class);
                if (commentBean.getMessage().getCode() == 200) {
                    recodeNum++;
                    CommonUtils.setBarTextView(tvBar, recodeNum);
                    showCenterInfoMsg("评论成功");
                    etInput.setText("");
                    parentId = "";
                    if (viewPager.getCurrentItem() == 0) {
                        viewPager.setCurrentItem(1);
                    } else if (viewPager.getCurrentItem() == 1) {
                        EventBus.getDefault().post(new KnowCommentRefreshEvent());
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() == 0) {
            finish();
        } else if (viewPager.getCurrentItem() == 1) {
            viewPager.setCurrentItem(0);
        }
    }

    @Override
    public void onResize(int w, int h, int oldw, int oldh) {
        //如果第一次初始化
        if (oldh == 0) {
            return;
        } //如果用户横竖屏转换
        if (w != oldw) {
            return;
        }
        if (h < oldh) {
            //输入法弹出
        } else if (h > oldh) {
            //输入法关闭
            llSend.setVisibility(View.GONE);
            llShow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        String s = charSequence.toString();
        if (TextUtils.isEmpty(s)) {
            cardSend.setCardBackgroundColor(getResources().getColor(R.color.color_ced5e0));
        } else {
            cardSend.setCardBackgroundColor(getResources().getColor(R.color.colorMain));
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void onException(int requestId, String code) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static void OpenActivity(Context context, String knowledgeId) {
        Intent intent = new Intent(context, KnowInformationActivity.class);
        if (context instanceof Application) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra("knowledgeId", knowledgeId);
        context.startActivity(intent);
    }
}
